<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>城市智慧系统 - 登录</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="container">
    <div class="form-container">
      <div class="form-box" id="loginForm">
        <h2>用户登录</h2>
        <form>
          <div class="input-group">
            <input type="text" id="loginUsername" name="loginUsername" required>
            <label for="loginUsername">用户名</label>
          </div>
          <div class="input-group">
            <input type="password" id="loginPassword" name="loginPassword" required>
            <label for="loginPassword">密码</label>
          </div>
          <div class="remember-forgot">
            <label><input type="checkbox"> 记住我</label>
            <a href="#" id="forgotBtn">忘记密码?</a>
          </div>
          <div id="loginMessage" class="message-box"></div>
          <button type="submit">登录</button>
        </form>
        <div class="switch-form">
          还没有账号? <a href="#" id="registerBtn">立即注册</a>
        </div>
      </div>

      <div class="form-box" id="registerForm">
        <h2>用户注册</h2>
        <form>
          <div class="input-group">
            <input type="text" id="regUsername" name="regUsername" required>
            <label for="regUsername">用户名</label>
          </div>
          <div class="input-group">
            <input type="email" id="regEmail" name="regEmail" required>
            <label for="regEmail">电子邮箱</label>
          </div>
          <div class="input-group">
            <input type="password" id="regPassword" name="regPassword" required>
            <label for="regPassword">密码</label>
          </div>
          <div class="input-group">
            <input type="password" id="regConfirmPassword" name="regConfirmPassword" required>
            <label for="regConfirmPassword">确认密码</label>
          </div>
          <div class="input-group select-group">
            <select id="regRole" name="regRole" required>
              <option value="">--请选择身份--</option>
              <option value="student">学生</option>
              <option value="teacher">教师</option>
            </select>
          </div>
          <div id="securityFields" class="conditional-fields">
            <div id="securityQuestionsContainer">
              <!-- 这里将由JS动态插入三组密保问题选择和答案输入 -->
            </div>
          </div>
          <div id="studentFields" class="conditional-fields">
            <div class="input-group">
              <input type="text" id="regRealName" name="regRealName" required>
              <label for="regRealName">真实姓名</label>
            </div>
            <div class="input-group">
              <input type="text" id="regStudentId" name="regStudentId" required>
              <label for="regStudentId">学号</label>
            </div>
            <div class="input-group">
              <input type="text" id="regDepartment" name="regDepartment" required>
              <label for="regDepartment">院系</label>
            </div>
            <div class="input-group">
              <input type="text" id="regClass" name="regClass" required>
              <label for="regClass">班级</label>
            </div>
          </div>
          <div id="teacherFields" class="conditional-fields">
            <div class="input-group">
              <input type="text" id="regTeacherName" name="regTeacherName" required>
              <label for="regTeacherName">真实姓名</label>
            </div>
            <div class="input-group">
              <input type="tel" id="regContactNumber" name="regContactNumber" required>
              <label for="regContactNumber">联系电话</label>
            </div>
          </div>
          <div id="registerMessage" class="message-box"></div>
          <button type="submit">注册</button>
        </form>
        <div class="switch-form">
          已有账号? <a href="#" id="loginBtn">立即登录</a>
        </div>
      </div>

      <div class="form-box" id="forgotForm">
        <h2>找回密码</h2>
        <form>
          <div class="input-group">
            <input type="email" id="forgotEmail" name="forgotEmail" required>
            <label for="forgotEmail">注册邮箱</label>
          </div>
          <div class="input-group select-group">
            <select id="forgotSecurityQuestion" name="forgotSecurityQuestion" required>
              <option value="">--请选择密保问题--</option>
              <option value="您的出生城市是?">您的出生城市是?</option>
              <option value="您的第一所学校名称是?">您的第一所学校名称是?</option>
              <option value="您的第一个宠物名字是?">您的第一个宠物名字是?</option>
              <option value="您母亲的姓名是?">您母亲的姓名是?</option>
              <option value="您父亲的姓名是?">您父亲的姓名是?</option>
              <option value="您最喜欢的电影是?">您最喜欢的电影是?</option>
              <option value="您的童年好友名字是?">您的童年好友名字是?</option>
              <option value="您的第一辆车的品牌是?">您的第一辆车的品牌是?</option>
            </select>
          </div>
          <div class="input-group">
            <input type="text" id="forgotSecurityAnswer" name="forgotSecurityAnswer" required class="no-underline">
            <label for="forgotSecurityAnswer">密保答案</label>
          </div>
          <div id="forgotMessage" class="message-box"></div>
          <button type="submit">发送重置链接</button>
        </form>
        <div class="switch-form">
          <a href="#" id="backToLoginBtn">返回登录</a>
        </div>
      </div>

      <div class="form-box" id="adminLoginForm">
        <h2>管理员登录</h2>
        <form>
          <div class="input-group">
            <input type="text" id="adminUsername" name="adminUsername" required>
            <label for="adminUsername">管理员账号</label>
          </div>
          <div class="input-group">
            <input type="password" id="adminPassword" name="adminPassword" required>
            <label for="adminPassword">密码</label>
          </div>
          <div id="adminLoginMessage" class="message-box"></div>
          <button type="submit">登录</button>
        </form>
        <div class="switch-form">
          <a href="#" id="backToLoginFromAdmin">返回普通登录</a>
        </div>
      </div>

      <div class="form-box" id="pendingApprovalForm">
        <h2>等待审核</h2>
        <div class="pending-message">
          <p>您的账号正在等待管理员审核，审核通过后即可登录。</p>
          <p>请耐心等待，您也可以联系管理员加快审核进度。</p>
        </div>
        <div class="switch-form">
          <a href="#" id="backToLoginFromPending">返回登录</a>
        </div>
      </div>
    </div>

    <div class="admin-link">
      <a href="#" id="adminLoginLink">管理员入口</a>
    </div>

  </div>

  <script src="script.js"></script>
  <script>
    document.querySelector('#forgotForm form').addEventListener('submit', async function (e) {
      e.preventDefault();
      const email = document.getElementById('forgotEmail').value;
      const securityQuestion = document.getElementById('forgotSecurityQuestion').value;
      const securityAnswer = document.getElementById('forgotSecurityAnswer').value;
      const res = await fetch('/api/forgot-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, securityQuestion, securityAnswer })
      });
      const data = await res.json();
      if (data.success) {
        showResetPasswordModal(data.userId, data.resetToken);
      } else {
        showAlert(data.message || '邮箱或密保信息不正确', 'error', 'forgotMessage');
      }
    });

    function showResetPasswordModal(userId, resetToken) {
      document.getElementById('forgotForm').innerHTML = `
        <h2>重置密码</h2>
        <form id="resetPasswordForm">
          <div class="input-group">
            <input type="password" id="newPassword" required>
            <label for="newPassword">新密码</label>
          </div>
          <div class="input-group">
            <input type="password" id="confirmNewPassword" required>
            <label for="confirmNewPassword">确认新密码</label>
          </div>
          <div id="forgotMessage" class="message-box"></div>
          <button type="submit">重置密码</button>
        </form>
        <div class="switch-form">
          <a href="#" id="backToLoginFromReset">返回登录</a>
        </div>
      `;
      document.getElementById('resetPasswordForm').onsubmit = async function (e) {
        e.preventDefault();
        const newPassword = document.getElementById('newPassword').value;
        const confirmNewPassword = document.getElementById('confirmNewPassword').value;
        if (newPassword !== confirmNewPassword) {
          showAlert('两次输入的密码不一致', 'error', 'forgotMessage');
          return;
        }
        const res = await fetch('/api/reset-password', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ userId, newPassword, token: resetToken })
        });
        const data = await res.json();
        if (data.success) {
          showAlert('密码重置成功，请重新登录', 'success', 'forgotMessage');
        } else {
          showAlert(data.message || '密码重置失败', 'error', 'forgotMessage');
        }
      };
    }

    document.getElementById('regRole').addEventListener('change', function () {
      const role = this.value;
      const securityFields = document.getElementById('securityFields');
      if (role !== 'admin' && role !== '') {
        securityFields.style.display = 'block';
      } else {
        securityFields.style.display = 'none';
      }
    });

    window.addEventListener('DOMContentLoaded', function () {
      const role = document.getElementById('regRole').value;
      const securityFields = document.getElementById('securityFields');
      if (role !== 'admin' && role !== '') {
        securityFields.style.display = 'block';
      } else {
        securityFields.style.display = 'none';
      }
    });

    document.querySelector('#registerForm form').addEventListener('submit', function (e) {
      const emailInput = document.getElementById('regEmail');
      const email = emailInput.value.trim();
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email)) {
        e.preventDefault();
        emailInput.focus();
        alert('请输入有效的电子邮箱地址');
        return false;
      }
    });

    const questionSelect = document.querySelector('.regSecurityQuestion');
    const answerInput = document.querySelector('.regSecurityAnswer');
    const securityQuestion = questionSelect ? questionSelect.value : '';
    const securityAnswer = answerInput ? answerInput.value.trim() : '';

    function showAlert(message, type, targetId) {
      const box = document.getElementById(targetId);
      if (!box) return;
      box.textContent = message;
      box.className = 'message-box ' + (type || 'error');
      box.style.display = 'block';
    }
  </script>
</body>

</html>